package com.sys.user.controller.adminuser;


import com.sys.core.page.Pagination;
import com.sys.core.utils.ConvertObj;
import com.sys.core.utils.UUIDUtils;
import com.sys.user.base.controller.BaseController;
import com.sys.user.domain.Xypermission;
import com.sys.user.service.XypermissionService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 *   菜单角色权限关系
 * Created by 汤伟杰 on 2017/5/23.
 */
@Controller
@RequestMapping("/xypermission")
public class XypermissionController extends BaseController<Xypermission> {
    @Autowired
    private XypermissionService xypermissionService;

    /** 列表 **/
    @RequestMapping("/list.do")
    public String list(Integer pageNo, Integer pageSize, Xypermission xypermission, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(xypermission,req,model);
        setMenuId(model);
        setRoleId(model);
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        try {
            Map<String, Object> params = ConvertObj.toMap(xypermission);
            Pagination pagination = xypermissionService.list(pageNo.intValue(), pageSize.intValue(), params, model);
            model.addAttribute("pagination", pagination);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed","获取菜单角色权限关系列表失败!"+e.getMessage());
        }
        model.addAttribute("entity", xypermission);
        return "xypermission/list";
    }
    /**
    * api接口菜单角色权限关系列表
    * @param pageNo
    * @param pageSize

    * @param req
    * @param resp
    * @param model
    * @throws Exception
    */
    @RequestMapping("/apiList.jn")
    public void apiList(Integer pageNo, Integer pageSize, Xypermission xypermission,
        HttpServletRequest req, HttpServletResponse resp,
        ModelMap model) throws Exception {
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        try {
            Map<String, Object> params = ConvertObj.toMap(xypermission);
            Pagination pagination = xypermissionService.apilist(pageNo.intValue(), pageSize.intValue(), params, model);
            jsonResult(1,"","",pagination,resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"","获取菜单角色权限关系列表失败!"+e,"",resp);
        }

    }
    /**
    * api接口菜单角色权限关系详情
    * @param req
    * @param resp
    * @param model
    * @throws Exception
    */
    @RequestMapping("/apiDetail.jn")
    public void apiDetail(HttpServletRequest req, HttpServletResponse resp,
    ModelMap model) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        Enumeration<String> enumeration = req.getParameterNames();
        if(enumeration.hasMoreElements()){
            String next = enumeration.nextElement();
            params.put(next, req.getParameter(next));
        }

        try {
            Map<String,Object> result = xypermissionService.getApiDetail(params);
            jsonResult(1,"","",result,resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"99","获取菜单角色权限关系详情失败!"+e,"",resp);
        }

    }
    /** api测试页面 **/
    @RequestMapping("/apiTest.do")
    public String apiList(HttpServletRequest req, HttpServletResponse resp,
        ModelMap model) throws Exception {
        model.addAttribute("entity",new HashMap<String,Object>());
        return "xypermission/apiTest";

    }

    /** 保存 **/
    @RequestMapping("/save.do")
    public String save(Xypermission xypermission,
                      HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        try {

            if(StringUtils.isNotBlank(xypermission.getPermissionId())){
                xypermissionService.update(xypermission);


            }else{
                xypermission.setPermissionId(UUIDUtils.getUUID());
                xypermissionService.insert(xypermission);
            }
            model.addAttribute("success", "保存菜单角色权限关系成功");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "保存菜单角色权限关系失败!详情："+e.getMessage());
        }
        return "redirect:list.do";
    }


    /** 详情 **/
    @RequestMapping("/detail.do")
    public String detail(@RequestParam(required = true)String permissionId, Xypermission xypermission, HttpServletRequest req, HttpServletResponse resp,
                         ModelMap model){
        setMsg(xypermission,req,model);
        setMenuId(model);
        setRoleId(model);
        try {
            Xypermission entity = xypermissionService.queryById(xypermission.getPermissionId());
            model.addAttribute("entity", entity);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "查询菜单角色权限关系出错!详情："+e.getMessage());
        }
        return "xypermission/detail";
    }
    /** 新增或修改 **/
    @RequestMapping("/add.do")
    public String add(Xypermission xypermission, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(xypermission,req,model);
        setMenuId(model);
        setRoleId(model);
        if(StringUtils.isNotBlank(xypermission.getPermissionId())){
            xypermission = xypermissionService.queryById(xypermission.getPermissionId());
            model.addAttribute("entity", xypermission);
        }
        return "xypermission/add";
    }
    /** 删除 **/
    @RequestMapping("/delete.do")
    public String delete(@RequestParam(required = true)String permissionId,Xypermission xypermission, HttpServletRequest req, HttpServletResponse resp,
                     ModelMap model){
        try {
            xypermissionService.deleteById(xypermission.getPermissionId());
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", e.getMessage());
        }
        return "redirect:list.do";
    }
    private void setMenuId(ModelMap model) {
        Map<String,Object> param = new HashMap<String,Object>();
        List<Map<String,Object>> listMenuId = xypermissionService.getListMenuId(param);
        // map.put("name","");
        // map.put("value","");
        model.addAttribute("listMenuId", listMenuId);
    }
    private void setRoleId(ModelMap model) {
        Map<String,Object> param = new HashMap<String,Object>();
        List<Map<String,Object>> listRoleId = xypermissionService.getListRoleId(param);
        // map.put("name","");
        // map.put("value","");
        model.addAttribute("listRoleId", listRoleId);
    }

    private void setMsg(Xypermission xypermission,HttpServletRequest req, ModelMap model) {
        model.addAttribute("failed", req.getParameter("failed"));
        model.addAttribute("success", req.getParameter("success"));
        model.addAttribute("entity", xypermission);
    }
    @RequestMapping("/updatepermission.do")
    public String updatepermission(@RequestParam(required = true) String roleId, HttpServletRequest req, ModelMap model) {
        List<Map<String,Object>> listmap = xypermissionService.AllMenuPermissionByRoleId(roleId);
//        xm.name,xp.roleId,xm.parentId,xm.menuId
        for (int i = 0; i < listmap.size(); i++) {
            if(listmap.get(i).get("roleId")!=null){
                listmap.get(i).put("ispermission",true);
            }else{
                listmap.get(i).put("ispermission",false);
            }
        }
        model.addAttribute("roleId",roleId);
        model.addAttribute("listmap",listmap);
        return "xypermission/updatepermission";
    }

    /**
     * 保存角色权限
     * @param roleId
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
    @RequestMapping("/saveMenu.do")
    public void saveMenu(@RequestParam(required = true) String roleId,

                         HttpServletRequest req, HttpServletResponse resp,
                         ModelMap model) throws Exception {
        String[] ids = req.getParameterValues("ids[]");
        List<String> liststr = new ArrayList<String>();
        if(ids!=null&&ids.length!=0){
            liststr = Arrays.asList(ids);
        }

        //根据角色查询权限关联
        List<Xypermission> list = xypermissionService.queryByRoleId(roleId);
        //删除权限关联
        List<String> listdel = new ArrayList<String>();
        for (Xypermission xypermission : list) {
            listdel.add(xypermission.getPermissionId());
        }
        //新增权限关联
        List<Xypermission> xypermissionList = new ArrayList<Xypermission>();

        for (String s : liststr) {
            Xypermission xypermission = new Xypermission();
            xypermission.setPermissionId(UUIDUtils.getUUID());
            xypermission.setMenuId(s);
            xypermission.setRoleId(roleId);
            xypermissionList.add(xypermission);
        }
        if(listdel.size()!=0){
            xypermissionService.deleteByIds(listdel);
        }

        if(xypermissionList.size()!=0){
            xypermissionService.saves(xypermissionList);
        }



    }
}
